using System;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.UIElements;

public class MenuPopupData
{
    public string label;
    public object obj;
    public Action<MenuPopupData> onback;
}

public class MenuPopup : SingletonBehaviour<MenuPopup>
{
    private UIDocument uiroot;
    private ListView listView;

    void Start()
    {
        uiroot = GetComponent<UIDocument>();
        listView = uiroot.rootVisualElement.Q<ListView>("MenuPopup");
        listView.style.display = DisplayStyle.None;

        // Callback invoked when the user double clicks an item
        listView.itemsChosen += (selectedItems) => { Debug.Log("Items chosen: " + string.Join(", ", selectedItems)); };

// Callback invoked when the user changes the selection inside the ListView
        listView.selectionChanged += OnSelectChenged;
    }

    private void OnSelectChenged(IEnumerable<object> selectedItems)
    {
        var data = (listView.selectedItem as MenuPopupData);
        if (data != null)
        {
            // Debug.Log("Items selected: " + string.Join(", ", selectedItems));
            data.onback(data);
            Invoke("Hide", 0.2f);
        }
    }

    private Vector2 pos;
    private List<MenuPopupData> ls;
    public void Show(Vector2 pos, List<MenuPopupData> ls)
    {
        this.pos = pos;
        this.ls = ls;
        Hide();
        if (ls == null && ls.Count == 0) return;
        Invoke("Ref",0.1f);
    }

    void Ref()
    {
        listView.transform.position = pos;
        listView.Clear();
        Func<VisualElement> makeItem = () => new Label();
        Action<VisualElement, int> bindItem = (e, i) =>
        {
            (e as Label).text = ls[i].label;
            e.AddToClassList("menuPopLabel");
        };

        listView.makeItem = makeItem;
        listView.bindItem = bindItem;
        listView.itemsSource = ls;
        listView.selectionType = SelectionType.Single;
        Invoke("SetFocus", 0.2f);
    }

    void SetFocus()
    {
        Show();
        listView.Focus();
    }

    void Hide()
    {
        if (listView.style.display == DisplayStyle.Flex)
        {
            listView.UnregisterCallback<BlurEvent>(OnLostFoucs);
            listView.style.display = DisplayStyle.None;
            listView.ClearSelection();
        }
    }

    void Show()
    {
        listView.RegisterCallback<BlurEvent>(OnLostFoucs);
        listView.style.display = DisplayStyle.Flex;
    }

    void OnLostFoucs(BlurEvent evt)
    {
        Debug.Log("lost focus in menupopup");
        Hide();
    }
}